Playing and mixing multiple sounds with aupyom

This notebook shows you how aupyom can be used to:

  • Load sounds either from audio file or from raw signal data
  • Create a sampler
  • Add and remove sound to the sampler

Loading sounds

Aupyom provides a Sound class used to load audio data either:

  • from an audio file (it uses librosa for IO)
  • from audio data (provided as a numpy array)

In [ ]:
from aupyom import Sound

You can directly load an audio file:


In [2]:
from aupyom.util import example_audio_file

audio_file = example_audio_file()
print(audio_file)


/Users/pierrerouanet/dev/aupyom/aupyom/example_data/Tom's Dinner.wav

In [3]:
s1 = Sound.from_file(audio_file)

And you can also directly feed the Sound class with numpy data. For instance, here we compute the well-known 440Hz sinusoid.


In [4]:
import numpy

freq = 440.0
sr = 22050
t = 10.0

s2 = Sound(numpy.sin(2 * numpy.pi * freq * numpy.linspace(0, t, sr * t)), sr)

Playing sounds

To play and mix your sounds together, you first need to create a Sampler. It uses portaudio as a backend to access your soundcard.

Note: as it accesses your soundcard, only one instance of Sampler should be opened at the same time.


In [5]:
from aupyom import Sampler

sampler = Sampler()

Then, to start playing sounds you just use:

Note that this method returns immediatly and does not wait for the sound to be entirely played. It only triggers the sound play.


In [6]:
sampler.play(s1)

You can access the playing property to check if a sound is currently played by the sampler.


In [7]:
s1.playing


Out[7]:
True

You can also access all played sounds via:


In [8]:
sampler.sounds


Out[8]:
[<aupyom.sound.Sound at 0x10aad0f98>]

You can play multiple sounds at a same time. Assuming s1 is still playing, you can mix it with s2:


In [9]:
sampler.play(s2)

s1 and s2 are automatically mixed.


In [10]:
sampler.remove(s1)

As illustrated below, there is no limitation on the number of sounds you can mix.


In [11]:
import numpy

def soundwave(f, t=10., sr=22050):
    return Sound(numpy.sin(2 * numpy.pi * freq * numpy.linspace(0, t, sr * t)), sr)
    
waves = [soundwave(440 * note) for note in range(1, 12)]

In [12]:
for w in waves:
    sampler.play(w)

Integration with notebook

Sound can also be played directly in the notebook as widget.


In [13]:
s1.as_ipywidget()


Out[13]: